/**
 * author: XGP
 * date: 2018/06/26
 * des: 登录相关api
 * 1.登录
 * 2.公钥
 * 3.登出
 */
import request from '@/utils/request'

/**
 * 登录
 * @param {*} username
 * @param {*} password
 */

export function loginByUsername(userName, password) {
  const data = {
    username: userName,
    pwd: password
  }
  const getPublic = new Promise((resolve, reject) => {
    getPublicKey().then((response) => {
      const publicKye = response.data
      const JSEncrypt = window.JSEncrypt
      const encrypt = new JSEncrypt()
      encrypt.setPublicKey(publicKye)
      data.password = encrypt.encrypt(data.pwd)
      delete data.pwd
      resolve(data)
    }).catch((err) => {
      reject(err)
    })
  })
  return new Promise((resolve, reject) => {
    getPublic.then((response) => {
      request({
        url: '/login',
        method: 'post',
        data: response
      }).then((res) => {
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    }).catch((err) => {
      reject(err)
    })
  })
}

/**
 * 获取加密公钥
 */
function getPublicKey() {
  return request({
    url: '/rsa-public-key',
    method: 'get'
  })
}

/**
 * 登出
 */
export function logout() {
  return request({
    url: '/logout',
    method: 'post'
  })
}

/**
 * 使用会话token获取用户信息
 */
export function getSessionUserApi() {
  return request({
    url: '/session-user',
    method: 'get'
  })
}

/**
 * 修改密码功能
 */
export function changeUserPwd(userName, oldPwd, newPwd, userId) {
  const params = {
    userName: userName,
    oldPwd: oldPwd,
    userPwd: newPwd
  }
  return request({
    url: '/system/users/'+ userId +'/password',
    method: 'put',
    data: params
  })
}
